package org.fffd.l23o6.util.strategy.payment;

import java.math.BigDecimal;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import io.github.lyc8503.spring.starter.incantation.exception.BizException;
import jakarta.validation.constraints.NotNull;
import org.fffd.l23o6.exception.BizError;
import org.fffd.l23o6.util.paystub.AlipayStub;
import org.fffd.l23o6.util.qrCode.Qrcode;
import org.fffd.l23o6.util.strategy.train.KSeriesSeatStrategy;

public class AlipayStrategy extends PaymentStrategy {
    public static final AlipayStrategy INSTANCE = new AlipayStrategy();
    private AlipayClient alipayClient;

    AlipayStrategy() {
        init();
    }

    @Override
    public int init() {
        String gatewayHost = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
        String signType = "RSA2";

        String appId = "9021000122698611";  //"<-- 请填写您的AppId，例如：2019091767145019 -->";

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCojrO9Oy7guODt1BnJMX23To77bFyE81x" +
                "2A1CFwcUExYTC1ldOqAyTaBw2RG0Eged/DujjsGN5FWd0xs0Qbb5MC4QrBvJ1fZq6u6tjBGNPHghxERivbTveui7EzI39CibJgUNPMwuzA" +
                "f1nZsi+h2e6kVZRBSn5LmMGsFYOxFl/0ktBOCOQe22iDvERT2KPXxPitOJ4cXys5dJvzZbzkwjGx9knYO24xOPPb5l/5qZuBG6zIXRyBC5" +
                "w7KnEPeSPAxZKET2UsAPmrUDe/VIpy3rHYasUHKuZQeaCa9yPhckcjfTPc61IuEpyX5lYLZjrDAHHEfxtZuycjH1fdAj9dserAgMBAAECg" +
                "gEBAI1A8V1uYG2QYWbNLULOx8S6/9WxTKNZ8i0vv+YnqTzDbet9hjLzX36Ua7gKhbWWS3LOAtr0cZgCGO3iv+y5mxTNPdh0/PD67pT4Ort" +
                "C7RpbV8WxBxfUGa0gJ5titMbOIA0T111isLY1v69MkoQgowvVShmhkzgv6GqtkaDUaRBUxEU8bIkT3c93W2ZvuM4Q+twfWdODjCf9YlZsl" +
                "E7nLNCIvR3yQD5aogPoUVaPqhHpjXyWRnJvwsrw6xjKN2E+0NduL501MbOye3/KTYmmVkHaWrXMH6LG9JluKCqM3QF3O11RKtuPonhHPnd" +
                "QR4CrRB9FPnZX9uzI8V8gL13H1aECgYEA5TAOtGyniK9ZFFJARn3FhQH0HTo5Kd4tOHU7sv0JmwRzo7QyEGid+hJZEiE7VFWDnwzD0Go9D" +
                "WH/xouWWUgX0mCOZCnz+omw00f2XsQDKkekaDp0ilyqHI1+OOd+EIYpP2TYqW+PnmBlJnC0yRL0uJX3/Ja/IXKdzUvNF4+ScHsCgYEAvEb" +
                "UAQU9IIRmv2efdmUvq0dFd4gOlpfql32Wown9l8R+bDA3zJmHowB0kqVaLfWG5/sbtkVqyMMF5k3CVNdFpXYhnZe9XFyd8GzPq+1QNDt6L" +
                "IbehkUA8ws1zBNKMnMM/oVRDedh981Dfd6WuoToVFy/agALlurIUgWdUerHlpECgYEAyR3g6YcnhRSKkQCUkscvm0ZZl4ROQWVMPWzy1GC" +
                "kGzpO1+r6u9dyOc38B6LN03WvKNUkyDFSHfpPX0WCzBotfVlp2o/OH57QYreVhRdwx5tStHwHZJtoU+H+T6UkxQ9WBuFSF21klFB2ssLYg" +
                "lJ2GbzQfwEx/AH+Y/cOpIxCrx0CgYALTT0gqo3Wy9vXFYNO+hf4chjLahFmHMxqN5G5S7o7SAJGwEY5M+YedMKKov5cz+Y/OqWZNWWJk5t" +
                "hDb3ileGKYyL1cMxfJPgeHIoCygYMfJ2C2r201aOO81dRXr8PdDSNerc43HDXDS1F+vyVSbEgj0i2NjZ74rAPrGKbLjq44QKBgF37mDVDQ" +
                "4MkeI+w3ogoAxKPCddeRT64XrbaHPUUe+2XNBK7cJDCQjobfYMAolqe2WSOjyMBQWsvZokHaIbhju8KrPWjOWi75wqpkcA78lFmYG7r3JM" +
                "Ed6xSaURDFPUn6DLT1exalrtFNo6LN674zQkvI+R3rULwRAUbi8kYm4Mk";
        //"<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->";

        //注：证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径，优先从文件系统中加载，加载失败后会继续尝试从CLASS_PATH中加载
//        config.merchantCertPath = "<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->";
//        config.alipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->";
//        config.alipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->";

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgfxzvtenwd7gZoofuemcdEmP20pRyG6VL0j7mbLw/F214" +
                "GMf0LiaFGoj++DeGNTN0caISDQerfvDsSAirv4b9gMq064P+PG4/r5WjdFl7VcFlhLrMXgxAmCUrFm4t4Kn29s7M9hrRdxDo/9Gam9hDQl" +
                "QgIU8k/gxVsr1ZkGLCZiIDTFUwkxf/b2/40WhgDJNgPFdxI60kDPF2ZqjlNGpaAUquFPvyfECtQEQK/o1bGd/huFenk2fsyxGo+hEqoww7" +
                "iR39F84hPde0tizSK+vBXdyObkPuh2i6MaqzYP7wChooSBtNyOiVsL8/NPE9XxrlOEjrKefbeV6eSXsctKc9QIDAQAB";
        //"<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->";

        //可设置异步通知接收服务地址（可选）
//        config.notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";

        alipayClient = new DefaultAlipayClient(gatewayHost, appId, privateKey,
                "json", "utf-8", alipayPublicKey, signType);

        return 0;
    }

    //TODO
    @Override
    public boolean pay(Long id, BigDecimal amount, Long userId) {
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        String outTradeNo = String.valueOf(System.currentTimeMillis());
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(amount.toPlainString());
        model.setSubject("车票");
        request.setBizModel(model);
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        Qrcode.generate(String.valueOf(id), response.getQrCode());

        AlipayTradeCreateRequest requestCreate = new AlipayTradeCreateRequest();
        AlipayTradeCreateModel modelCreate = new AlipayTradeCreateModel();
        modelCreate.setOutTradeNo(outTradeNo);
        modelCreate.setSubject("车票");
        modelCreate.setTotalAmount(String.valueOf(amount));
        modelCreate.setBuyerId("2088722004658857");
        modelCreate.setTimeoutExpress("30m");
        requestCreate.setBizModel(modelCreate);
        try {
            AlipayTradeCreateResponse responseCreate = alipayClient.execute(requestCreate);
            System.out.println(responseCreate.getBody());
            if (responseCreate.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }

        //使用桩的情形
        AlipayStub.PayResult result = AlipayStub.pay(amount);
        if (result == AlipayStub.PayResult.LACK_OF_BALANCE) {
            throw new BizException(BizError.OUT_OF_MONEY);
        }
        if (result == AlipayStub.PayResult.ERROR) {
            throw new BizException(BizError.PAYMENT_FAILURE);
        }

        //使用支付宝官方接口
        AlipayTradeQueryRequest requestQuery = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel modelQuery = new AlipayTradeQueryModel();
        modelQuery.setOutTradeNo(outTradeNo);
        requestQuery.setBizModel(modelQuery);
        AlipayTradeQueryResponse responseQuery;
        for (int i = 0; i < 10; ++i) {
            try {
                Thread.sleep(2000);
                responseQuery = alipayClient.execute(requestQuery);
                if (responseQuery.isSuccess()) {
                    System.out.println("调用成功");
                    System.out.println(responseQuery.getTradeStatus());
                } else {
                    System.out.println("调用失败");
                }
                if (responseQuery.getTradeStatus().equals("TRADE_SUCCESS")
                        || responseQuery.getTradeStatus().equals("TRADE_FINISHED")) {
                    i = 10;
                }
            } catch (Exception e) {
                System.err.println("调用遭遇异常，原因：" + e.getMessage());
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        return false;
    }

    @Override
    public boolean refund(BigDecimal amount) {
        AlipayStub.PayResult result = AlipayStub.refund(amount);
        if (result == AlipayStub.PayResult.ERROR) {
            throw new BizException(BizError.REFUND_FAILURE);
        }

        return false;
    }
}
